Page({
  data: {
    searchKeyword: '',
    searchHistory: [],
    hotSearchList: [],
    displayHotSearch: [],
    showAllHotSearch: false,
    suggestions: [],
    searchResults: [],
    loading: false
  },

  onLoad() {
    this.loadSearchHistory();
    this.loadHotSearch();
  },

  // 加载搜索历史
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },

  // 更新显示的热门搜索
  updateDisplayHotSearch() {
    const displayCount = this.data.showAllHotSearch ? 10 : 5;
    this.setData({
      displayHotSearch: this.data.hotSearchList.slice(0, displayCount)
    });
  },

  // 从后端加载热门搜索（取前10个关键词，去重）
  loadHotSearch() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/search_logs/list',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: { pageNum: 1, pageSize: 100 },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const rows = res.data.rows || [];
          const counter = new Map();
          rows.forEach(item => {
            const kw = (item.keyword || '').trim();
            if (!kw) return;
            counter.set(kw, (counter.get(kw) || 0) + 1);
          });
          const sorted = Array.from(counter.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 10)
            .map(([kw]) => ({ keyword: kw, isHot: true }));
          this.setData({ hotSearchList: sorted });
          this.updateDisplayHotSearch();
        }
      },
      fail: (err) => {
        console.error('加载热门搜索失败', err);
      }
    });
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    
    if (keyword) {
      this.getSearchSuggestions(keyword);
    } else {
      this.setData({
        suggestions: [],
        searchResults: []
      });
    }
  },

  // 获取搜索建议
  // getSearchSuggestions(keyword) {
  //   // 模拟搜索建议
  //   const suggestions = [
  //     `${keyword}的做法`,
  //     `${keyword}菜谱`,
  //     `${keyword}家常菜`,
  //     `${keyword}简单做法`,
  //     `${keyword}营养搭配`
  //   ];
    
  //   this.setData({
  //     suggestions: suggestions
  //   });
  // },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value || this.data.searchKeyword;
    if (keyword.trim()) {
      this.performSearch(keyword);
    }
  },

  // 执行搜索
  performSearch(keyword) {
    this.setData({
      loading: true,
      searchResults: []
    });

    // 保存搜索历史
    this.saveSearchHistory(keyword);

    // 调用后端菜谱搜索接口
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/recipes/list',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        pageNum: 1,
        pageSize: 10,
        title: keyword
      },
      success: (res) => {
        const rows = (res.data && res.data.code === 200) ? (res.data.rows || []) : [];
        const results = rows.map(item => {
          let imageUrl = 'https://picsum.photos/300/200?random=1';
          if (item.mediaType === 2) {
            imageUrl = item.videoDescription ? `http://localhost:8080${item.videoDescription}` : imageUrl;
          } else if (item.mediaType === 1) {
            imageUrl = item.coverUrl ? `http://localhost:8080${item.coverUrl}` : imageUrl;
          }
          return {
            id: item.id,
            title: item.title || '',
            imageUrl: imageUrl,
            authorName: (item.users && item.users.nickname) ? item.users.nickname : '美食达人',
            authorAvatar: (item.users && item.users.avatarUrl) ? `http://localhost:8080${item.users.avatarUrl}` : 'https://picsum.photos/60/60?random=1',
            collectCount: item.collectCount || 0
          };
        });

        this.setData({
          searchResults: results,
          loading: false
        });

        // 成功后记录搜索日志（仅当有结果时）
        if (results.length > 0) {
          this.logSearchKeyword(keyword);
        }
      },
      fail: (err) => {
        console.error('搜索失败', err);
        this.setData({ loading: false });
        wx.showToast({ title: '搜索失败', icon: 'none' });
      }
    });
  },

  // 生成搜索结果
  generateSearchResults(keyword) {
    const mockResults = [
      {
        id: 1,
        title: `${keyword}的做法大全`,
        imageUrl: 'https://picsum.photos/300/200?random=1',
        authorName: '不会做饭的西瓜',
        authorAvatar: 'https://picsum.photos/60/60?random=1',
        likes: 1234
      },
      {
        id: 2,
        title: `简单${keyword}菜谱`,
        imageUrl: 'https://picsum.photos/300/200?random=2',
        authorName: '美食达人',
        authorAvatar: 'https://picsum.photos/60/60?random=2',
        likes: 856
      },
      {
        id: 3,
        title: `${keyword}营养搭配`,
        imageUrl: 'https://picsum.photos/300/200?random=3',
        authorName: '营养师小李',
        authorAvatar: 'https://picsum.photos/60/60?random=3',
        likes: 567
      },
      {
        id: 4,
        title: `${keyword}家常做法`,
        imageUrl: 'https://picsum.photos/300/200?random=4',
        authorName: '妈妈的味道',
        authorAvatar: 'https://picsum.photos/60/60?random=4',
        likes: 789
      }
    ];

    return mockResults;
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = this.data.searchHistory;
    
    // 移除已存在的相同关键词
    history = history.filter(item => item !== keyword);
    
    // 添加到开头
    history.unshift(keyword);
    
    // 限制历史记录数量
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    
    this.setData({
      searchHistory: history
    });
    
    // 保存到本地存储
    wx.setStorageSync('searchHistory', history);
  },

  // 清空输入
  onClearInput() {
    this.setData({
      searchKeyword: '',
      suggestions: [],
      searchResults: []
    });
  },

  // 取消搜索
  onCancelTap() {
    wx.navigateBack();
  },

  // 清空历史记录
  onClearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            searchHistory: []
          });
          wx.removeStorageSync('searchHistory');
          wx.showToast({
            title: '已清空',
            icon: 'success'
          });
        }
      }
    });
  },

  // 查看更多热门搜索
  onViewMoreTap() {
    this.setData({
      showAllHotSearch: !this.data.showAllHotSearch
    });
    this.updateDisplayHotSearch();
  },

  // 点击历史搜索标签
  onHistoryTagTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchKeyword: keyword
    });
    this.performSearch(keyword);
  },

  // 点击热门搜索标签
  onHotSearchTagTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchKeyword: keyword
    });
    this.performSearch(keyword);
  },

  // 点击搜索建议
  onSuggestionTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchKeyword: keyword
    });
    this.performSearch(keyword);
  },

  // 点击搜索结果
  onResultTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/index/pages/search-result/search-result?id=${id}&keyword=${this.data.searchKeyword}`
    });
  }
,

  // 记录搜索关键字到后端
  logSearchKeyword(keyword) {
    let token = '';
    let userId = null;
    try {
      token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo') || {};
      userId = userInfo.id || null;
    } catch (e) {
      console.error('读取用户信息失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/search_logs',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        userId: userId,
        keyword: keyword
      }
    });
  }
}); 